
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.StyleContext;
import javax.swing.text.Element;
import java.awt.*;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JTextPane;

public class Panel2A extends JPanel {

    //int num; //Z
    boolean newfile = true;
    boolean changed = false;
    boolean cancel = false;
    boolean nothingReadIn =false;
    myChooser choose; // choose open file
    static String neededType = "txt"; // filter
    static int listenuper; // command
    //static int i; //Z
    //static int j = 1; //Z
    //static int n; //Z
    //JPanel contain; //Z
    //protected StyleContext m_context; // Z
    //protected DefaultStyledDocument m_doc; // Z
    //final JTextPane textArea; // Z
    public String filename;
    File address;
    CodingPane my;

    public Panel2A() {

        setLayout(new BorderLayout(5, 10));

        my=new CodingPane();
		
        choose = new myChooser("."); // create a filechooser in default directory
        
        choose.addChoosableFileFilter(new neededFil(neededType));//set neededType = "txt" for the filter of the chooser;
  
        JScrollPane sp = new JScrollPane(my);

        setLocation(200, 200);

        setVisible(true);

        add(sp, BorderLayout.CENTER);
    }
	/**
	 * @author Kai Li
	 * this method is used for recognize the file name, when saving or reading
	 * if the user has not type the extension, the methods automatically add the extension
	 */
    public File getFileName() {
        boolean end_with_txt = false; // to determine whether the file name ends with extension
        int index = choose.getSelectedFile().getName().lastIndexOf('.');
        if (index > 0 & index < (choose.getSelectedFile().getName().length() - 1)) { //to catch the extension of the file
            String extension = choose.getSelectedFile().getName().substring(index + 1).toLowerCase();
            if (extension.equals(neededType)) { // if the extension of this file is the same as the extension that can pass
                end_with_txt = true; // it has the extension
            } else {
                end_with_txt = false; // it has no extension
            }
        }
        if (end_with_txt) { 
            return new File(choose.getCurrentDirectory(), choose.getSelectedFile().getName()); // the file name is not changed
        } else {
            return new File(choose.getCurrentDirectory(), choose.getSelectedFile().getName() + ".txt"); // add extension to the file name
        }
    }
	/**
	 * @author Shangru Li
	 * this method is used for saving a file as a new name in another directory
	 */
    public void saveas() {
        try {
            // save the data in the direction selected with the name user input
            int result = choose.showSaveDialog(this);
            File fileToSaveAs = this.getFileName();
            if (result == JFileChooser.APPROVE_OPTION) {//if the user clicks the save in Chooser
                
                FileWriter filewriter = new FileWriter(fileToSaveAs);
                BufferedWriter bffwriter = new BufferedWriter(filewriter);

                String gt = my.getText();
                //String gt = textArea.getText(); //use a string to read in all the text in the selected tab
                bffwriter.write(gt, 0, gt.length()); //write the string from the beginning to the end in the file
                bffwriter.flush();
                filewriter.close();//complete the writing process
                filename = choose.getSelectedFile().getName();//update the file name to be the file name user typed in the chooser
                address = choose.getCurrentDirectory();// update the address to be the saved address
                changed = false;// indicate the file has not changed after saving
                newfile = false; // indicate the file is no longer a new file that has never been saved before
            }
            

        } catch (Exception e1) {
        }

    }
	/**
	 * @author Shangru Li
	 * this method is used for saving a file in its original directory with its original name
	 */
    public void save() {
        try {
            // save the data in the direction selected with the name user input

            //if the user clicks the save in Chooser
            File fileToSave = new File(address, filename);
            FileWriter filewriter = new FileWriter(fileToSave); // use a filewirter to write the file
            BufferedWriter bffwriter = new BufferedWriter(filewriter);

            String gt = my.getText();
            //String gt = textArea.getText(); //use a string to read in all the text in the selected tab
            bffwriter.write(gt, 0, gt.length()); //write the string from the beginning to the end in the file
            bffwriter.flush();
            filewriter.close(); //complete the writing process
            filename = choose.getSelectedFile().getName();//update the file name to be the file name user typed in the chooser
            address = choose.getCurrentDirectory(); // update the address to be the saved address
            changed = false; // indicate the file has not changed after saving
            newfile = false; // indicate the file is no longer a new file that has never been saved before

        } catch (Exception e1) {
        }


    }
	/**
	 * @author Shangru Li
	 * this method is used for reading a file in
	 */
    public void read() {
        String templine; // a string to read a line of the file 
        String all; // a string to record all the content of the file
        try { //use a buffer reader to read in the file selected
            File fileToRead = this.getFileName();

            FileReader filereader = new FileReader(fileToRead); // use a filereader to read the file
            BufferedReader bffreader = new BufferedReader(filereader);

            all = ""; // initialize the string to be blank
            while ((templine = bffreader.readLine()) != null) { // if there is a line, read the line in the templine

                all = all + templine + '\n'; // all is the original"all" plus new templine plus an "enter"

            }
            my.setText(all);
            //textArea.setText(all); // set the text field to be the content of all

            filereader.close();
            newfile = false;

        } catch (Exception e1) {
        }
        filename = choose.getSelectedFile().getName();// record the file name
        address = choose.getCurrentDirectory(); //record the file address
    }
	/**
	 * @author Shangru Li
	 * @param listenuper the command number from upper class
	 * this method is used for determining which of the function will be performed
	 */
    public void fileAction(int listenuper) {
        this.listenuper = listenuper;
        
        if (listenuper == 1) { // if the user wants to read new file

            choose.opening = true; // indicate the beginning of the open new file process
            int result = choose.showOpenDialog(this); // create a chooser for the user to choose a file
            if (result == JFileChooser.APPROVE_OPTION) { // if the user confirm to read in
                this.read(); // invoke the read method
                //System.out.println(filename);
            }
            else{
            	nothingReadIn=true;
            }
            choose.opening = false; // indicate the end of the reading new file process


        }
        if (listenuper == 2) { // if the user want to save this file
            if (newfile) { // if it is a new file created in this program
                this.saveas(); // invoke the saveas method
                
            } else {// if the file was read from the hard disk 
                this.save(); // invoke the save method
                

            }
        }
        if (listenuper == 3) { // if the user want to save the file in a new directory with a new name
            this.saveas(); // invoke the saveas method
            newfile = false; // indicate the file is no longer a new file that has never been saved before


        }
        if (listenuper == 4) {
            if (my.textChange()) { // if some change has occurred to the file after last time of saving
                int copy = JOptionPane.showConfirmDialog(null, "The file has not yet saved, save it?", // ask the user whether to save it
                        "save", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
                if (copy == JOptionPane.CANCEL_OPTION){
                	
                 cancel=true;
                	
                }
                
                if (copy != JOptionPane.CANCEL_OPTION) { // if the user do not want to cancel

                
                    cancel=false;
               
                    if (copy == JOptionPane.YES_OPTION) { // if the user want to save it before closing

                        if (newfile) { // if the file has never been saved in the hard disk
                            this.saveas(); // invoke the saveas method
                            newfile = false; //indicate the file has been saved
                        } else {// if the file has been saved in the hard disk before
                            this.save(); // invoke the save method
                            newfile = false; // indicate the file has been saved

                        }

                    }


                    my.setText("");
                    //textArea.setText(""); // set the text field to be blank
                    newfile = true; // indicate that the new file has not been saved in the hard disk
                    changed = false; // indicate the file has not been changed yet
                }
            }
            }
        }
    

    public JTextPane getTextPane() {
        return my.textPane;  // ?
    }
    
    public void setText(String s){    //WANG Jiechao   in order to get the text in the Group class
    	my.setText(s);
    }

}
